$(function() {
    //工单类型下拉菜单
    $.get(projectPath + '/base/constss/list?code=1000000010', function (r) {
        var data = r.data;
        var value = '<option value="">--请选择--</option>';
        $(data).each(function(index,r){
            value += '<option value="'+r.constvalue+'">'+r.constname+'</option>';
        })
        $("#targetType").append(value);
    });
    $('#tb_ads').bootstrapTable({
        method: 'POST',                      //请求方式（*）
        url:projectPath + "/base/workorders/donelist",
        contentType: 'application/x-www-form-urlencoded',
        toolbar: '#toolbar',                //工具按钮用哪个容器
        striped: true,                      //是否显示行间隔色
        cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        pagination: true,                   //是否显示分页（*）
        sortable: false,                     //是否启用排序
        sortOrder: "asc",                   //排序方式
        search:false,
        queryParams: dataQueryParams,//传递参数（*）
        sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
        pageNumber: 1,                       //初始化加载第一页，默认第一页
        pageSize: 10,                       //每页的记录行数（*）
        pageList: [10,20,50],        //可供选择的每页的行数（*）
        strictSearch: true,
        clickToSelect: false,                //是否启用点击选中行
        uniqueId: "id",
        showColumns: true,                  //是否显示所有的列
        showRefresh: true,                  //显示刷新按钮
        showToggle: true,
        minimumCountColumns: 2,             //最少允许的列数
        singleSelect:true,
        paginationPreText: "上一页",
        paginationNextText: "下一页",
        columns: [
            // {field: 'check', checkbox: true},
            {field: '', title: '序号', align: 'center', formatter: function (value, row, index) {
                var pageSize=$('#tb_ads').bootstrapTable('getOptions').pageSize;//通过表的#id 可以得到每页多少条
                var pageNumber=$('#tb_ads').bootstrapTable('getOptions').pageNumber;//通过表的#id 可以得到当前第几页
                return pageSize * (pageNumber - 1) + index + 1;    //返回每条的序号： 每页条数 * （当前页 - 1 ）+ 序号
            }},
            {field: 'uuid', title: '主键', align: 'center', visible:false},
            {field: '', title: '资产码/批次号',align: 'center',formatter: function (value, row, index) {
                    if(row.targettype == "registrationApply"){ // 注册码
                        value = row.registrationApplyNo
                    }else {
                        value = row.stakeNo
                    }
                    return "<div style='white-space: nowrap;'>" + value + "</div>";
                }},
            {field: 'workorderno', title: '工单编号',align: 'center',formatter: function (value, row, index) {
                return '<div style="white-space: nowrap;"><a href="javascript:;" onclick="workOrderDetail(\''+row.targettype+'\',\''+row.workstatus+'\',\''+row.targetuuid+'\',\''+row.uuid+'\')">' + value + '</a></div>';
            }},
            {field: 'content', title: '工单类型',align: 'center',formatter: function (value, row, index) {
                return '<div style="white-space: nowrap;">'+ value +'</div>';
            }},
            {field: 'createorgName', title: '产权单位',align: 'center',formatter: function (value, row, index) {
                return "<div style='white-space: nowrap;'>" + value + "</div>";
            }},
            {field: 'createdat', title: '创建时间',align: 'center',formatter: function (value, row, index) {
                if(value == "" || value == null){
                    value="";
                }else{
                    value = getLocalTime(value);
                };
                return "<div style='white-space: nowrap;'>" + value + "</div>";
            }},
            {field: 'reviewrdate', title: '处理时间',align: 'center',formatter: function (value, row, index) {
                if(value == "" || value == null){
                    value="";
                }else{
                    value = getLocalTime(value);
                };
                return "<div style='white-space: nowrap;'>" + value + "</div>";
            }},
            {field: 'reviewrName', title: '处理人',align: 'center',formatter: function (value, row, index) {
                return '<div style="white-space: nowrap;">'+ value +'</div>';
            }},
            {field: 'workstatus', title: '当前状态', align: 'center',formatter: function (value, row, index) {
                if(row.targettype == "registrationApply"){ // 注册码
                    if(value == 10001){
                        value = "待审核"
                    }else if(value == 10004){
                        value = "审核拒绝"
                    }else if(value == 10005){
                        value = "审核通过"
                    }
                }else if(row.targettype == "maintenanceApply"){ // 桩维护
                    if(value == 10001){
                        value = "资产台账待维护"
                    }else if(value == 10002){
                        value = "已提交(待审核)"
                    }else if(value == 10005){
                        value = "审核已通过"
                    }
                }else if(row.targettype == "maintenaceCharge"){ // 桩审核
                    if(value == 10001){
                        value = "待审核"
                    }else if(value == 10004){
                        value = "审核拒接"
                    }else if(value == 10005){
                        value = "审核通过"
                    }
                }
                return "<div style='white-space: nowrap;'>" + value + "</div>";
            }},
        ],
        responseHandler: function (data) {
            return {
                total:data.data.total,
                rows:data.data.list
            }
        }
    });
    //开始时间
    $('#startTime').datetimepicker({
        language:  'zh-CN',
        format: 'yyyy-mm-dd',
        weekStart: 1,
        autoclose: 1,
        todayBtn: 1,
        initialDate:new Date(),
        startView: 2,
        minView: 2,
        forceParse: 0,
        pickerPosition:'bottom-right',
    }).on("changeDate",function(e){
        if(e.date != null&&e.date != ''){
            var startTime = Dateinit.getNextDay(e.date); //2018-03-10 14:47
        }
        //前一天与后一天时间的比较清空
        var start2 = new Date(Date.parse($('#startTime').val().replace(/-/g,"/"))); // 中国标准时间
        if(Date.parse(startTime.replace(/-/g,"/"))> start2){
            $("#endTime").val('');
        }
        //设置结束时间的起始值未开始时间的下一天
        $("#endTime").datetimepicker("setStartDate",startTime);
    });
    //结束时间
    $('#endTime').datetimepicker({
        language:  'zh-CN',
        format: 'yyyy-mm-dd',
        weekStart: 1,
        autoclose: 1,
        todayBtn: 1,
        startView: 2,
        minView: 2,
        forceParse: 0,
        pickerPosition:'bottom-right',
    });
    //查询
    $("#btnQuery").click(function(){
        $('#tb_ads').bootstrapTable('refresh', {url: projectPath + '/base/workorders/donelist',pageNumber:1});
    });
    // 清空
    $("#btnEmpty").click(function(){
        $("#workorderNo").val(""); // 工单编号
        $("#startTime").val("");
        $("#endTime").val("");
        $("#targetType").val(""); // 工单类型
        $("#createorgCode").attr("data-id","");
        $("#createorgCode").val("");
    });

    // 产权单位弹窗选择
    $("#prorgcodeClick").on("click",function () {
        initOrgTreeLayer("0","选择产权单位","createorgCode");
    });
});

function dataQueryParams() {
    var filterinfo = {};
    if($("#workorderNo").val() != ""){
        filterinfo.workorderNo = $("#workorderNo").val(); // 工单编号
    };
    if($("#startTime").val() != ""){
        filterinfo.createdAtStart = $("#startTime").val(); // 开始时间
    };
    if($("#endTime").val() != ""){
        filterinfo.createdAtEnd = $("#endTime").val(); // 结束时间
    };
    if($("#targetType").val() != ""){
        filterinfo.targetType = $("#targetType").val(); // 工单类型
    };
    if($("#createorgCode").attr("data-id") != ""){
        filterinfo.createorgCode = $("#createorgCode").attr("data-id"); // 产权单位
    };
    filterinfo.offset = (this.pageNumber-1)*this.pageSize;
    filterinfo.limit = this.pageSize;
    return filterinfo;
};


/*-------------------------------------已办工单详情查看-----------------------------*/

// 工单详情查看
function workOrderDetail(targettype,workstatus,targetuuid,uuid){
    alert(workstatus);
    alert(targetuuid);
    alert(uuid + "工单id")
    if(targettype == "registrationApply"){ // 注册码
        var indexReg = layer.open({
            type: 1,
            title: "注册码",
            shadeClose: true,
            shade: 0.3,
            area: ['100%', '100%'],
            skin: 'layui-layer-rims',
            content: $(".registrationApply"),
            closeBtn:1,
            shadeClose:false,
            fixed:false,
            resize:true,
            maxmin:true,
            success:function(){
                regisDetail(targetuuid);
            },
            cancel:function(){
                layer.close(indexReg);
            }
        });
        // 关闭
        $("#btnCloseRegis").unbind().on("click",function(){
            layer.close(indexReg);
        });
    }else if(targettype == "maintenanceApply"){ // 桩维护
        var indexApply = layer.open({
            type: 1,
            title: "充电桩维护申请",
            shadeClose: true,
            shade: 0.3,
            area: ['100%', '100%'],
            skin: 'layui-layer-rims',
            content: $(".stakeSafeOrAudit"),
            closeBtn:1,
            shadeClose:false,
            fixed:false,
            resize:true,
            maxmin:true,
            success:function(){
                stakeDetail(targetuuid);
            },
            cancel:function(){
                layer.close(indexApply);
            }
        });
        // 关闭
        $("#btnCloseStake").unbind().on("click",function(){
            layer.close(indexApply);
        });
    }else if(targettype == "maintenaceCharge"){ // 桩审核
        var indexCharge = layer.open({
            type: 1,
            title: "充电桩维护审核",
            shadeClose: true,
            shade: 0.3,
            area: ['100%', '100%'],
            skin: 'layui-layer-rims',
            content: $(".stakeSafeOrAudit"),
            closeBtn:1,
            shadeClose:false,
            fixed:false,
            resize:true,
            maxmin:true,
            success:function(){
                stakeDetail(targetuuid);
            },
            cancel:function(){
                layer.close(indexCharge);
            }
        });
        // 关闭
        $("#btnCloseStake").unbind().on("click",function(){
            layer.close(indexCharge);
        });
    }
};

/* 注册码详情 */
function regisDetail(targetuuid){
    $.ajax({
        type: "POST",
        url:projectPath+'/base/registration/applys/detail?id='+targetuuid,
        async:false,
        dataType:"json",
        success:function(result){
            var data = result.data;
            console.log(data);
            $("#prorgcode").val(data.prorgcode); // 产权 申请人所在单位
            $("#apply").val(data.prorgcode); // 申请单位
            $("#creatorUuid").val(data.creatorname); // 申请人
            $("#applyAmount").val(data.amount); // 申请数量
            $("#acceptedAmount").val(data.amount); // 下发数量
            $("#stakeType").val(data.staketype); // 充电桩类型
            $("#remark").val(data.remark); // 申请备注

            // 电费
            var chargerfeemodelcode = data.chargerfeemodelcode;
            // 服务
            var servicefeemodelcode = data.servicefeemodelcode;
            getChargerfeemodelcode(chargerfeemodelcode);
            getServicefeemodelcode(servicefeemodelcode);
        },
        error:function(){
            layerAlert.errorMessage("不好意思，数据出错啦！");
        }
    })
};

// 电费
function getChargerfeemodelcode(chargerfeemodelcode){
    $.ajax({
        type: "GET",
        url:projectPath+'/base/chargerfeemodels?id=' + chargerfeemodelcode,
        async:false,
        dataType:"json",
        contentType:"application/json",
        success:function(result){
            var data = result.data.list[0];
            console.log(data);
            if(result.data.list.length>0){
                $("#sharpFee").val(data.sharpfee);
                $("#sharpZone").val(data.sharpzone);
                $("#overShootFee").val(data.overshootfee);
                $("#overShootZone").val(data.overshootzone);
                $("#flatFee").val(data.flatfee);
                $("#flatZone").val(data.flatzone);
                $("#valleyFee").val(data.valleyfee);
                $("#valleyZone").val(data.valleyzone);
            }
        },
        error:function(){
            layerAlert.errorMessage("不好意思，数据出错啦！");
        }
    })
};

// 服务费
function getServicefeemodelcode(servicefeemodelcode){
    $.ajax({
        type: "GET",
        url:projectPath+'/base/servicefeemodels?id=' + servicefeemodelcode,
        async:false,
        dataType:"json",
        contentType:"application/json",
        success:function(result){
            var data = result.data.list[0];
            if(result.data.list.length>0) {
                $("#serverSharpFee").val(data.sharpfee);
                $("#serverOverShootFee").val(data.overshootfee);
                $("#serverFlatFee").val(data.flatfee);
                $("#serverFalleyFee").val(data.valleyfee);
            }
        },
        error:function(){
            layerAlert.errorMessage("不好意思，数据出错啦！");
        }
    })
};


/* 桩详情 */
function stakeDetail(targetuuid){
    $.ajax({
        type: "POST",
        url:projectPath+'/base/stakes/detail?id='+targetuuid,
        async:false,
        dataType:"json",
        success:function (data) {
            debugger;
            result = data.data;
            console.log(result);
            $("#stakeNos").val(result.stakeno); // 桩编号
            $("#stakename").val(result.stakename); // 桩名称(字段中的别名)
            if(result.runtime == null || result.runtime == ""){
                $("#runtime").val(""); // 投运时间
            }else{
                $("#runtime").val(getLocalTime(result.runtime)); // 投运时间
            };
            $("#authcode").val(result.authcode); // 授权码
            $("#registrationNo").val(result.registrationNo); // 注册码
            if(result.useAt == null || result.useAt == ""){
                $("#registdat").val("");     // 注册时间
            }else{
                $("#registdat").val(getLocalTime(result.useAt));     // 注册时间
            };
            if (result.productionDate == null || result.productionDate == "") {
                $("#createdat").val(""); // 生产时间
            } else {
                $("#createdat").val(getLocalTime(result.productionDate)); // 生产时间
            };
            $("#factoryno").val(result.outFactoryDateNo);                    // 出厂编号
            $("#durableyears").val(result.durableYears); //使用年限
            $("#stakeTypes").val(result.staketype); // 桩类型(公专)
            $("#typeinfo").val(result.type); // 设备类型
            $("#status").val(result.status); // 桩标记
            // 接口标准初始化
            if (result.type == "1") { // 直流
                $.ajax({
                    type: "get",
                    async:false,
                    url: projectPath + '/base/constss/list?code=30005052',
                    success:function (data) {
                        debugger;
                        console.log(data);
                        $("#standard").empty();
                        $("#standard").append('<option value="">--请选择--</option>');
                        $("#standard").append('<option value="'+ data.data[0].constvalue +'">'+ data.data[0].constname +'</option>');
                    }
                });
            } else if (result.type == "2") { // 交流
                $.ajax({
                    type: "get",
                    async:false,
                    url: projectPath + '/base/constss/list?code=30005051',
                    success:function (data) {
                        debugger;
                        console.log(data);
                        $("#standard").empty();
                        $("#standard").append('<option value="">--请选择--</option>');
                        $("#standard").append('<option value="'+ data.data[0].constvalue +'">'+ data.data[0].constname +'</option>');
                    }
                });
            };
            if(result.debuggingtime == null || result.debuggingtime == ""){
                $("#debuggingtime").val(""); // 调试时间
            }else{
                $("#debuggingtime").val(getLocalTime(result.debuggingtime)); // 调试时间
            };
            $("#standard").val(result.standard);
            $("#standards").selectpicker('val', result.chargeStandard); // 充电标准
            $('#standards').selectpicker('refresh');
            var tradetypes = result.tradetypes;
            var groupCheckbox = $("input[name='tradeTypes']");
            for (var i = 0; i < groupCheckbox.length; i++) {
                if (isInArray(tradetypes, groupCheckbox[i].value)) {
                    groupCheckbox[i].checked = true;
                    groupCheckbox[i].disabled = false;
                }
            }; // 交易类型

            // 获取站设备停车位uuid为后续传值获取详情
            var stationuuid = result.stationuuid;
            var equipmodeluuid = result.equipmodeluuid;
            var parkingareauuid = result.parkingareauuid;
            getStationTemplate(stationuuid);
            getEquipmentTemplate(equipmodeluuid);
            getParkAreaTemplate(parkingareauuid);
            getChargeGunTemplate(targetuuid);
        },
        error:function () {
            layerAlert.errorMessage("不好意思，数据出错啦！");
        }
    });
}

// 站详情
function getStationTemplate(stationuuid){
    if(stationuuid == null || stationuuid == "" ){
        return;
    };
    // 站信息回显
    $.ajax({
        type: "GET",
        url:projectPath+'/base/stations/'+stationuuid,
        async:false,
        dataType:"json",
        success:function (data) {
            var result = data.data;
            $("#stationnameInfo").val(result.stationname); // 站名称
            $("#stationnameInfo").attr("uuid",result.uuid); // 站名称

            $("#provinceCityPartInfo").val(result.partOrgName); // 组织机构
            $("#address").val(result.address); // 站地址
            $("#isthird").val(result.isthird); // 三方
            $("#stationType").selectpicker('val',((result.isthird==0||result.isthird==1)?"0":"1")+"-"+result.stationtype); // 站点类型
            $('#stationType').selectpicker('refresh');

            $("#lat").val(result.lat); // 经度
            $("#lng").val(result.lng); // 纬度
            $('#operatoruuid').selectpicker('val', result.operatoruuid);//运营商设置选中
            $('#operatoruuid').selectpicker('refresh');

            $("#servicephone").val(result.servicephone); // 服务电话
            $("#prorgCode").val(result.prOrgName); // 产权单位
        },
        error:function () {
            layerAlert.errorMessage("不好意思，数据出错啦！");
        }
    });
};

// 设备型号详情
function getEquipmentTemplate(equipmodeluuid){
    // 设备型号信息回显
    $.ajax({
        type: "POST",
        url: projectPath + '/base/equipment/infos/detail?id=' + equipmodeluuid,
        async:false,
        dataType:"json",
        success:function (data) {
            result = data.data;
            if(result != null){
                $("#equipmentno").val(result.equipmentname); //设备型号
                $("#vendoruuid").val(result.vendorName); //生产厂商
                $("#vendoruuid").attr("datauuid",result.vendoruuid);
                $("#maxoutvolt").val(result.maxoutvolt); //最大电压
                $("#power").val(result.power); //额定功率
            }
        },
        error:function () {
            layerAlert.errorMessage("不好意思，数据出错啦！");
        }
    })
};

// 停车区详情
function getParkAreaTemplate(parkingareauuid){
    // 停车区信息回显
    $.ajax({
        type: "POST",
        url:projectPath+'/base/parking/areas/detail?id='+parkingareauuid,
        async:false,
        dataType:"json",
        success:function (data) {
            var result = data.data;
            if(result || result != null) {
                $("#parkAreaNameInfo").val(result.name);// 选择停车区
                $("#parkareauuid").val(result.uuid); // 区uuid
                $("#parkingfee").val(result.parkingfee); // 收费标准
                $("#openat").val(result.openat); // 开放时间
                $("#closeat").val(result.closeat); //关闭时间
                $("#parkareauuid").change();
            }
        },
        error:function () {
            layerAlert.errorMessage("不好意思，数据出错啦！");
        }
    });
};

var nthTabs;
// 充电枪详情
function getChargeGunTemplate(targetuuid){
    // 充电枪信息回显
    nthTabs = $("#editor-tabs").nthTabs({allowClose:false});
    $.ajax({
        type: "POST",
        url:projectPath+'/base/chargers/queryChargersByStakeUuid?stakeUuid='+targetuuid,
        async:false,
        dataType:"json",
        success:function (data) {
            var result = data.data;
            console.log(result);
            if (result || result != null){
                if(spaceList == null){
                    getSpaceList();
                };
                if(equTypeList == null){
                    getEquTypeList();
                }
                for(var i = 0, length1 = result.length; i < length1; i++){
                    var dataHtml = '';
                    dataHtml += '<div class="col-md-12" style="margin-top: 20px;">';
                    dataHtml += '<div class="col-md-12 form-group"> <input type="hidden" name="chargeruuid" value="'+result[i].uuid +'"/>';
                    dataHtml += '<div class="col-md-4 col-sm-4 col-xs-4 "><label class="label-width1">充电枪编号:</label><input type="text" readonly class="form-control" value="'+ result[i].chargerno +'"></div>';
                    dataHtml += '<div class=" col-md-4 col-sm-4 col-xs-4 "><label class="label-width1">枪资产编码:</label><input type="text" readonly class="form-control" value="'+ result[i].assetNo +'"></div>';

                    dataHtml += '<div class=" col-md-4 col-sm-4 col-xs-4 "><label class="label-width4">设备接口类型:</label><select class="form-control" name="type" disabled>';
                    if(equTypeList != null){
                        for(var k = 0;k<equTypeList.length; k++){
                            dataHtml += "<option value='"+equTypeList[k].constvalue+"'";
                            if(result[i].type == equTypeList[k].constvalue){
                                dataHtml += "selected";
                            }
                            dataHtml +=">"+equTypeList[k].constname+"</option>";
                        }
                    }
                    dataHtml += '</select></div></div><div class="col-md-12 form-group">';
                    dataHtml += '<div class="col-md-4 col-sm-4 col-xs-4"><label class="label-width1">关联停车位:</label><select class="form-control" name="parkSpaceSelect" disabled>';
                    if(spaceList != null){
                        for (var j =0 ;j<spaceList.length;j++){
                            dataHtml +="<option value='"+spaceList[j].uuid+"'";
                            if( result[i].spaceuuid == spaceList[j].uuid){
                                dataHtml +=" selected";
                            }
                            if(result[i].bindedCharger == "1"){
                                dataHtml +=" title='该停车位已绑定，不可选择！' style='background-color: red;' disabled";
                            }
                            dataHtml +=">"+spaceList[j].name+"</option>";
                        }
                    }
                    dataHtml += '</select></div>';
                    dataHtml += '</div></div>';
                    nthTabs.addTab({
                        id:result[i].uuid,
                        title:"充电枪" + result[i].chargerno,
                        content:dataHtml
                    });
                    if(i == 0){
                        nthTabs.setActTab(result[i].uuid);
                    }
                };
            };
        },
        error:function () {
            layerAlert.errorMessage("不好意思，数据出错啦！");
        }
    });
};

// 关联停车位初始化
var spaceList = null;
function getSpaceList(){
    $.ajax({
        url: projectPath + '/base/parking/spaces/listByArea?parkingAreaUuid=' + $("#parkareauuid").val(),
        type: 'POST',
        dataType: 'json',
        async:false,
        success: function (data) {
            spaceList = data.data
        },
        error: function () {
            layerAlert.errorMessage("出错了");
        }
    });
}

// 设备接口类型初始化
var equTypeList = null;
function getEquTypeList(){
    $.ajax({
        url: projectPath + '/base/constss/list?code=1000000002',
        type: 'GET',
        dataType: 'json',
        async:false,
        success: function (data) {
            equTypeList = data.data
        },
        error: function () {
            layerAlert.errorMessage("出错了");
        }
    });
};

// 导出
$("#btnExport").on("click",function(){
    layer.open({
        type: 1,
        title: "选择导出页数",
        shadeClose: true,
        shade: 0.3,
        move :false,
        area: ['300px', '250px'],
        skin: 'layui-layer-rims',
        content: $(".export_dialog"),
        btn:['确定'],
        closeBtn:1,
        success:function(){
            $('.export_dialog').empty();
            //var endPage=pageCount;
            //var startPage=1;
            var str=[
                '<div class="form-group" style="margin-top:30px;margin-left: 10px;">',
                '<label class="label-width3">起始页:</label><input type="text"  class="form-control" id="start_page" value="1" />',
                '</div>',
                '<div class="form-group" style="margin-top: 10px;margin-left: 10px;">',
                '<label class="label-width3">结束页:</label><input type="text"  class="form-control" id="end_page" value="1000"/>',
                '</div>',
            ].join('');
            $('.export_dialog').append(str);
        },
        close:function(){
            $('.export_dialog').remove(str);
        },
        btn1:function(){
            alert("导出成功");
        }
    });
});